import agconnect from "@hw-agconnect/api"
import "@hw-agconnect/auth"
import "@hw-agconnect/instance"
import { ElMessage } from 'element-plus'
import { userInfoStore } from "../userStore/userStore";

class Auth {
    getVerifyCode(phone_num: string): Promise<boolean> {
        let promise: Promise<boolean> = new Promise<boolean>((resolve, reject) => {
            agconnect.auth().requestPhoneVerifyCode('+86',
                phone_num,
                agconnect.auth.Action.ACTION_REGISTER_LOGIN,
                'zh_CN',
                60)
                .then((_reslut) => {
                    resolve(true);
                    ElMessage({
                        message: `验证码发送成功，${_reslut.getShortestInterval()}s内有效`,
                        type: 'success',
                    })
                })
                .catch((error) => {
                    reject(error);
                    if (error.ret.code === 203818048) {
                        ElMessage.error('验证码发送时间间隔过短')
                    }
                });
        });
        return promise;
    }

    loginByVerifyCode(phone_num: string, verify_code: string) {
        const credential = agconnect.auth.PhoneAuthProvider.credentialWithVerifyCode('+86', phone_num, '', verify_code);
        return agconnect.auth().signIn(credential);
    }

    logOut() {
        agconnect.auth().signOut();
        const userStore = userInfoStore()
        userStore.$reset()
    }

    async getCurrectUser() {
        return agconnect.auth().getCurrentUser()
    }
}

export let agcAuth: Auth = new Auth();